package com.zhuhjay.service.system.wxmp.handler;

import com.zhuhjay.common.wxmp.builder.TextBuilder;
import com.zhuhjay.common.wxmp.handler.AbstractHandler;
import com.zhuhjay.service.system.model.entity.SystemOauth;
import com.zhuhjay.service.system.model.entity.SystemUser;
import com.zhuhjay.service.system.service.SystemConfigService;
import com.zhuhjay.service.system.service.SystemOauthService;
import com.zhuhjay.service.system.service.SystemUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ZhuHJay
 * @date 2023/8/2 19:48
 */
@Slf4j
@Component
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private SystemOauthService oauthService;
    @Resource
    private SystemUserService userService;
    @Resource
    private SystemConfigService configService;

    @Override
    public WxMpXmlOutMessage handle(
            WxMpXmlMessage wxMessage, Map<String, Object> context, 
            WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {

        String openid = wxMessage.getFromUser();
        SystemOauth oauth = oauthService.lambdaQuery().eq(SystemOauth::getOpenId, openid).one();
        StringBuilder sb = new StringBuilder();
        if (oauth != null) {
            SystemUser user = userService.getById(oauth.getUserId());
            sb.append("欢迎回来，系统用户【").append(user.getUsername()).append("】");
            oauth.setStatus(1);
            oauthService.lambdaUpdate().update(oauth);
        } else {
            sb.append("欢迎关注，系统访问地址：").append(configService.getConfigValue("system.front.base.url"));
        }
        return new TextBuilder().build(sb.toString(), wxMessage, wxMpService);
    }

}
